var doctorMap; //医生资料
var inquiryMap; //诊断信息
var nPageIndex;
var fileArr = [];
var prescription_id;//处方ID号

//获取问诊详情
function getInquiryLogDetails() {
	var paramJson = {
		"id": log_id
	};
	newAjaxPost("/h5/inquiryLog/getAllInfo", paramJson, getInquiryLogDetailsOk);
	return false;
}

function didRead(){
	parent.wsConnection.send(39, {
		"userId": doctor_imid, //发送方id
		"friendId": patientIM //接收方id
	})
}

function getInquiryLogDetailsOk(jsonInfo) {
	if (jsonInfo.code == '1') {
		var data = jsonInfo.data;
		// console.log(data);
		patientIdcard = data.patientIdcard;
		oldDoctorName = data.doctorName;
		doctorHeadImg = data.doctorHeadImg;
		isCompleted = data.isCompleted 					//可以用于判断是否点击已完成按钮
		inquiryType = data.inquiryType 					//问诊方式 1.图文 2.视频 3.家庭 4.复诊
		patientName = data.patientName 					//患者名称
		truename = data.patientName;
		if (data.patientImg) {
			patientImg = data.patientImg
		}
		else {
			patientImg = "../res/images/user_default.png"
		}
		if (data.acceptsTime) {
			console.log(1);
			$("#btnRefund").hide()
			// $('#btnEnd').show()
		}
		else {

		}

		// doctorMap = data.doctorMap; //医生资料
		// inquiryMap = data.inquiryMap; //诊断信息lrsj
		var guidanceList = data.inquiryLogHealthGuidanceList; 		//健康指导列表
		var hospitalizationList = data.hospitalizationDetailResp; 	//住院建议
		var formList = data.formListResult; 						//申请单列表
		var prescriptionList = data.prescriptionList; 				//处方列表
		var checklistList = data.inspectionOpinionList; 			//检验单列表

		// setLogTime(data.acceptsTime);
		$(".record_id").text(nothinglrsj(data.acceptsTime) + data.id);
		$(".patient_name").text(data.patientName); //姓名
		$(".patient_sex").text(data.patientSex == 1 ? "男" : "女"); //性别
		$(".pay_type").text(data.paymentMethod == '2' ? "医保缴费" : "自费缴费"); //付费类型
		// $(".pay_type").text("自费缴费"); //付费类型
		$(".patientAge").text(data.patientAge + '岁'); //年龄
		$(".inquiry_patient_phone").text(data.patientPhone); //手机号
		var is_married = data.isMarried == '0' ? "未婚" 
			: data.isMarried == '1' ? "已婚" 
			: data.isMarried == '2' ? "离婚"
			: "丧偶" ;
		$(".is_married").text(is_married);
		if (isUndefinedAndEmpty(data.patientWeight)) {
			var inquiry_patient_weight = '未提供';
		} else {
			var inquiry_patient_weight = data.patientWeight + 'kg';
		}
		$(".patient_marital_status").text(nothingFun(data.patientMaritalStatus, '未提供')); //籍贯
		$(".patient_weight").text(inquiry_patient_weight); //体重

		$(".doctor_name").text(data.doctorName); //就诊医生
		$(".department_name").text(data.departmentName); //医疗科室
		$(".doctor_work_address").text(data.hospitalName); //医疗机构
		$(".inquiry_patient_profession").text(nothingFun(data.patientProfession, '未提供')); //职业
		$(".inquiry_patient_address").text(nothingFun(data.patientAddress, '未提供')); //住址
		if (data.isDrugAllergy == 0) {
			$(".iinquiry_patient_allergy_details").text('无'); //过敏史
			// data.patientAllergyDetails = '';
		} else {
			$(".iinquiry_patient_allergy_details").text(nothingFun(data.patientAllergyDetails, '是，未提供')); //过敏史
		}
		$(".log_main_suit").text(nothingFun(data.mainSuit, '无')); //主诉
		$(".log_present_illness").text(nothingFun(data.presentIllness, '无')); //现病史
		$(".log_history_present_illness").text(nothingFun(data.historyPresentIllness, '无')); //既往史
		if (data.diagnosisArray) {
			var diagnosislist = '';
			for (var i = 0; i < data.diagnosisArray.length; i++) {
				if (i != 0) { diagnosislist += '、' }
				diagnosislist += data.diagnosisArray[i].diagnosis;
			}
			$(".lof_diagnosis").text(diagnosislist); //诊断
		} else {
			$(".lof_diagnosis").text('无'); //诊断
		}
		// $(".lof_diagnosis").text(nothingFun(data.diagnosis, '无')); //诊断
		$(".lrsj").text(data.acceptsTime); //就诊时间
		//1.处方列表
		prescriptionListC = '';
		if (prescriptionList && prescriptionList.length > 0) {
			$(".onlineRecipe").css('display', 'flex')
			// $.each(prescriptionList, function (e, item) {
			for (var i = 0; i < prescriptionList.length; i++) {
				if (prescriptionList[i].prescriptionType == 1) {
					prescriptionList[i].prescriptionType = "(中)"
					var prescriptiontype = '中药处方'
				}
				if (prescriptionList[i].prescriptionType == 2) {
					prescriptionList[i].prescriptionType = "(西)"
					var prescriptiontype = '西药处方'
				}
				prescriptionListC += `<div data-index="1" data-id="${prescriptionList[i].id}" class="showChat">${prescriptiontype} No：${prescriptionList[i].prescriptionNo}</div>`;
			}
			$(".prescriptionListC").html(prescriptionListC);
		}

		//2.检验检查
		checklistListC = '';
		var prescription_guidance = '';
		if (checklistList && checklistList.length > 0) {
			for (var i = 0; i < checklistList.length; i++) {
				checklistListC += `<div data-index="2" data-id="${checklistList[i].id}" class="showChat">检验检查 No：${checklistList[i].applicationFormNo}</div>`;
			}
		}
		else
			checklistListC = '暂无检验检查';
		$(".checklistListC").html(checklistListC)

		//健康指导
		guidanceListC = '';
		if (guidanceList && guidanceList.length > 0) {
			for (var i = 0; i < guidanceList.length; i++) {
				guidanceListC += `<div data-index="3" data-id="${guidanceList[i].id}" class="showChat">健康指导 No：${guidanceList[i].healthGuidanceNo}</div>`;
			}
		}
		else
			guidanceListC = "暂无健康指导";
		$(".guidanceListC").html(guidanceListC);

		//住院建议
		var hospitalizationListC = '';
		if (hospitalizationList != null) {
			// $.each(hospitalizationList, function (e, item) {
			hospitalizationListC += `<div data-index="4" data-id="${inquirypatientId}" class="showChat">住院建议书</div>`;
			// })
		}
		else
			hospitalizationListC = "暂无住院建议";
		$(".hospitalizationListC").html(hospitalizationListC);

		//申请单
		var formListResultC = '';
		if (formList && formList.length > 0) {
			for (var i = 0; i < formList.length; i++) {
				formListResultC += `<div data-index="5" data-id="${formList[i].id}" data-template="${formList[i].templateValue}" class="showChat">申请单 No：${formList[i].applicationFormNo}</div>`;
			}
		}
		else
			formListResultC = "暂无申请单";
		$(".formListResultC").html(formListResultC);

		// 获取历史信息
		if (first == 1) {
			getHistoryMsg()
			first = 0
		}
	}
	else { msgInfo(jsonInfo.info); }

	$('.showChat').on("click", function () {
		msgInfo('正在加载中');
		var paramJson;
		nPageIndex = $(this).data('index');
		pageId = $(this).data('id');
		paramJson = {
			'id': pageId,
			"type": 2
		}
		if (nPageIndex == 1) {			//处方
			paramJson.resourceType = 4;
		} else if (nPageIndex == 2) {
			paramJson.resourceType = 3;
		} else if (nPageIndex == 3) {
			paramJson.resourceType = 2;
		} else if (nPageIndex == 4) {
			paramJson.resourceType = 1;
			paramJson.id = log_id
		} else if (nPageIndex == 5) {
			paramJson.resourceType = 5;
			paramJson.template = $(this).data('template');;
		}
		setTimeout(function () {
			$(".close-popup-btn").click()
			newAjaxPost('/h5/pdf/getEstablishPdf', paramJson, showChatPageOk);
		}, 500);
		// newAjaxPost('/h5/pdf/getEstablishPdf', paramJson, showChatPageOk);
	})
}

function showChatPageOk(jsonInfo) {
	if (jsonInfo.code == 1) {
		var imgUrl, pageTitle;
		var data = jsonInfo.data;
		// $('.title').html(pageTitle);
		$('.imgShow').attr("src", data.url);
		$("#divRecordImg").removeClass('weui-popup__container--visible')
		$("#divRecordImg").popup(); //打开
		
		// if((log_type == 1 || log_type == 2)){  //医生已结束问诊 且 实时问诊
			document.getElementById('imgPopClose').addEventListener('click', reShowEndPop)
		// }
	}
	else
		msgInfo(jsonInfo.info);
}

function reShowEndPop(){	//再次拉起评价弹窗
	document.getElementById('imgPopClose').removeEventListener('click', reShowEndPop)

	setTimeout(() => {
		if(reShowFlag == 'record'){
			$('#divRecord').popup()
		}else if (reShowFlag == 'end'){
			$("#divEndInquiry").popup()
		}
	}, 200);
}

//获取历史聊天信息,渲染
function getHistoryMsg() {
	var params = {
		"friendId": doctor_imid,
		"id": '',
		"userId": patientIM
	}
	newAjaxPost("/h5/dectorEndInquiry/getChatRecordList", params, getHistoryMsgOk);
}
function getHistoryMsgOk(res) {
	// console.log(res);
	if (log_id) {

	}
	else {
		log_id = res.data[res.data.length - 1].inquiryLogId
	}
	var onemsg = '';
	var history = res.data;
	if (history.length > 0) {
		for (var i = 0; i < history.length; i++) {
			if($("#" + history[i].id).html()) {
				continue
			}
			
			if (history[i].userId == patientIM) {	//自己发的信息
				if (history[i].msgType == 3) {				//自己发过的图片
					onemsg += `
						<div class="onemsgUser1 onemsgUser ${history[i].isRead == 0 ? 'notRead' : 'isRead'}" style="display: flex; flex-direction: row-reverse; padding-right: 5px;" id="${history[i].id}" type="${history[i].msgType}">
							<div class="msgImgDiv" style="padding: 16px 0px;">
								<img class="msgImg" src = "${patientImg}" style="width: 30px;"></img>
							</div>
							<div class="msgPDiv" style="background: #2b73cc; border: 1px solid #EFF3F4; border-radius: 7px; padding: 4px; margin: 7px; max-width: 70%; position: relative;">
								<p class="msghead" style="color:white;">[${truename}] ${history[i].msgDate}</p>
								<p class="msgbody">
									<img class="msgImg openBig" src="${history[i].msgText}"></img>
								</p>
								<div class="delete_btn" id="id${history[i].id}" num="${history[i].id}" date="${history[i].msgDate}">撤回</div>
							</div>
						</div>`
				} else if (history[i].msgType == 0) {				//自己发过的消息
					onemsg += `
						<div class="onemsgUser1 onemsgUser ${history[i].isRead == 0 ? 'notRead' : 'isRead'}" style="display: flex; flex-direction: row-reverse; padding-right: 5px;" id="${history[i].id}">
							<div class="msgImgDiv" style="padding: 16px 0px;">
								<img class="msgImg" src = "${patientImg}" style="width: 30px;"></img>
							</div>
							<div class="msgPDiv" style="background: #2b73cc; border: 1px solid #EFF3F4; border-radius: 7px; padding: 4px; margin: 7px; max-width: 70%; position: relative;">
								<p class="msghead" style="color:white;">[${truename}] ${history[i].msgDate}</p>
								<p class="msgbody">
									<pre style="white-space: pre-wrap; white-space:pre-line; word-wrap: break-word; width: 100%; overflow: hidden;color:white;">${history[i].msgText}</pre>
								</p>
								<div class="delete_btn" id="id${history[i].id}" num="${history[i].id}" date="${history[i].msgDate}">撤回</div>
							</div>
						</div>`
				} else if (history[i].msgType == 4) {		//自己撤回的消息
					onemsg += `
						<div class="onemsgUser1" style="width: 100%;" id="${history[i].id}">
							<div class="msgPDiv" style="background: #EFF3F4; border: 1px solid #EFF3F4; border-radius: 7px; padding: 4px; margin: 7px auto;text-align: center; font-size: 12px; max-width: 60%;">
								<pre style="white-space: pre-wrap; white-space:pre-line; word-wrap: break-word; width: 100%; overflow: hidden;">${history[i].msgText}</pre>
							</div>
						</div>`
				}
				else if (history[i].msgType == 6) {
					if (history[i].msgText.indexOf("和患病时长【起病至就诊的时间】") != -1 || history[i].msgText.indexOf("医生已结束问诊") != -1) {
						onemsg += `
							<div class="onemsg" style="display: flex; width: 98%;padding-left: 5px;" id="${history[i].id}">
								<div class="msgImgDiv" style="padding: 16px 0px;">
									<img class="msgImg" src =${doctorHeadImg} style="width: 30px;"></img>
								</div>
								<div class="msgPDiv" style="background: #EFF3F4; border: 1px solid #EFF3F4; border-radius: 7px; padding: 4px; margin: 7px; max-width: 70%;">
									<p class="msghead" style="color:black;">[${oldDoctorName}] ${history[i].msgDate}</p>
									<p class="msgbody">
										<pre style="white-space: pre-wrap; white-space:pre-line; word-wrap: break-word; width: 100%; overflow: hidden;font-size: 15px;font-family: PingFang SC;font-weight: 500;color: #353535;">
											${history[i].msgText}</pre>
									</p>
								</div>
							</div>`
					}
					else if (history[i].msgText.indexOf("回答完毕记得点击下方【已完成") != -1) {
						onemsg += `
							<div class="onemsg" style="display: flex; width: 98%;padding-left: 5px;" id="${history[i].id}">
								<div class="msgImgDiv" style="padding: 16px 0px;">
									<img class="msgImg" src =${doctorHeadImg} style="width: 30px;"></img>
								</div>
								<div class="msgPDiv" style="background: #EFF3F4; border: 1px solid #EFF3F4; border-radius: 7px; padding: 4px; margin: 7px; max-width: 70%;">
									<p class="msghead" style="color:black;">[${oldDoctorName}] ${history[i].msgDate}</p>
									<p class="msgbody">
										<pre style="white-space: pre-wrap; white-space:pre-line; word-wrap: break-word; width: 100%; overflow: hidden;font-size: 15px;font-family: PingFang SC;font-weight: 500;color: #353535;">
											${history[i].msgText}
										</pre>
										<p style="width:20%;text-align: center;background: #1189FF;border-radius: 6px;font-size: 14px;font-family: PingFang SC;font-weight: bold;
											color: #FEFEFE;margin:5px 0;padding:5px 2px" id="isFinish" inquiryLogId=${history[i].inquiryLogId}>已完成</p>
									</p>
								</div>
							</div>`
					}
					else if (history[i].msgText.indexOf("您可选择离线等待本次问诊哦！") != -1) {
						onemsg += `
							<div class="onemsg" style="display: flex; width: 98%;padding-left: 5px;" id="${history[i].id}">
								<div class="msgImgDiv" style="padding: 16px 0px;">
									<img class="msgImg" src=${doctorHeadImg} style="width: 30px;"></img>
								</div>
								<div class="msgPDiv" style="background: #EFF3F4; border: 1px solid #EFF3F4; border-radius: 7px; padding: 4px; margin: 7px; max-width: 70%;">
									<p class="msghead" style="color:black;">[${oldDoctorName}] ${history[i].msgDate}</p>
									<p class="msgbody">
										<pre style="white-space: pre-wrap; white-space:pre-line; word-wrap: break-word; width: 100%; overflow: hidden;font-size: 15px;font-family: PingFang SC;font-weight: 500;color: #353535;">${history[i].msgText}</pre>
									</p>
								</div>
							</div>`
					}
				}
			}
			else {								//对方发的信息
				if (history[i].msgType == 5) {	//系统消息
					onemsg += `
						<div class="onemsg" style="width: 98%;padding-left: 5px;" id="${history[i].id}">
							<div class="msgPDiv" style="background: #EFF3F4; border: 1px solid #EFF3F4; border-radius: 7px; padding: 4px; margin: 7px auto;text-align: center; font-size: 12px; max-width: 60%;">
									<pre style="white-space: pre-wrap; white-space:pre-line; word-wrap: break-word; width: 100%; overflow: hidden;">${history[i].msgText}</pre>
							</div>
						</div>`
				}
				else {
					onemsg += `
						<div class="onemsg" style="display: flex; width: 98%;padding-left: 5px;" id="${history[i].id}">
							<div class="msgImgDiv" style="padding: 16px 0px;">
								<img class="msgImg" src="${doctorHeadImg}" style="width: 30px;"></img>
							</div>
							<div class="msgPDiv" style="background: #EFF3F4; border: 1px solid #EFF3F4; border-radius: 7px; padding: 4px; margin: 7px; max-width: 70%;">
								<p class="msghead" style="color:black;">[${history[i].msgUserName}] ${history[i].msgDate}</p>
								<p class="msgbody">`
					if (history[i].msgType == 3) {
						onemsg += `	<img class="msgImg openBig" src="${history[i].msgText}"></img>`
					} else {
						onemsg += `	<pre style="white-space: pre-wrap; white-space:pre-line; word-wrap: break-word; width: 100%; overflow: hidden;">${history[i].msgText}</pre>`
					}
					if (/(请等待药师审核|药师已审核通过)/.test(history[i].msgText)) {
						onemsg += `	<p style="font-size: 15px;font-family: PingFang SC;font-weight: 500;color: #1189FF;" class="goList">查看处方等清单></p>`
					}
					onemsg += `		
								</p>
							</div>
						</div>`
				}
			}
		}
		$("#chat_Log").append(onemsg);

		$(".goList").click(function () {
			// var inquiryLogId = $(this).attr("inquiryLogId")

			// goPage("my_prescription_list.htm?logId=" + inquiryLogId)
			goPage("my_prescription_list.htm?logId=" + log_id)
		})

		if (inquiryType == 3 || inquiryType == 4) {
			var finishBtn = document.querySelectorAll("#isFinish")
			if (isCompleted == 1) {
				//已经填了已完成
				finishBtn.forEach((item) => {
					item.style.background = '#F6F6F6'
					item.style.color = '#1189FF'
					item.click = null;
				})
			} else {
				//点击发送已完成信息
				var time = formatDate(new Date());
				finishBtn.forEach((item, index) => {
					if (index == (finishBtn.length - 1)) {
						item.addEventListener('click', () => {
							parent.wsConnection.send(30, {
								"logId": log_id, //问诊[id
								"userIm": patientIM, // 患者im
								"doctorIm": doctor_imid, // 医生imID		
							})
							parent.wsConnection.send(3, {
								'msgText': "医生已经收到您的信息啦~若医生还没回复，您可选择离线等待本次问诊哦！", // 信息体
								'friendId': patientIM, // 患者imID
								'inquiryLogId': log_id, //问诊iD log_id
								'msgusername': truename, //医生名字
								'msgType': 6,
								'msgDate': time
							})
							getInquiryLogDetails()
							getHistoryMsg()
						})
					} else {
						item.style.background = "#F6F6F6";
						item.style.color = "#1189FF";
						item.click = null;
					}
				})
			}
		}
		else {
			var finishBtn = document.querySelectorAll("#isFinish")
			finishBtn.forEach((item) => {
				item.style.background = '#F6F6F6'
				item.style.color = '#1189FF'
				item.click = null;
			})
		}

		if(history[history.length - 1].msgUserName == oldDoctorName){	//如果最后一条消息是医生的 可能是新消息 发送一次已读
			didRead()
		}

		$(".goList").click(function () {
			goPage("my_prescription_list.htm?logId=" + log_id)
		})
		// 300ms后,等待图片加载完，滚动条自动滚动到底部
		setTimeout(function () {
			scrollBottom()
			$(".openBig").on('click', function () {
				var imgsrc = $(this)[0].src
				$('.show').attr('src', imgsrc)
				$('.img_mask').addClass('weui-mask--visible');
				$('.img_dialog').addClass('weui-dialog--visible');
			})
			$(".close_img").on('click', function () {
				$('.img_mask').removeClass('weui-mask--visible')
				$('.img_dialog').removeClass('weui-dialog--visible')
			})
		}, 300);
	}
}


//结束问诊
function endInquiry() {
	//  TRTC.closeVideo()
	var zh_val = $("input[name='pf']:checked").val(),
		zl_val = $("input[name='zl']:checked").val(),
		td_val = $("input[name='td']:checked").val(),
		xt_val = $("input[name='xt']:checked").val()

	var comment_detail = $("#commentDetail").val(),
		advice = $("#complaint").val();

	var userJson = strToJson(localStorage.getItem('DSXBuserJson'));

	var zz_val = $("input[name='zz']:checked").val(),
		wm_val = $("input[name='wm']:checked").val(),
		zj_val = $("input[name='zj']:checked").val(),
		yb_val = $("input[name='yb']:checked").val();

	// if(isUndefinedAndEmpty(comment_detail)) {
	// 	msgInfo('请输入评价内容');
	// 	return false
	// }

	var paramJson = {
		"evaluate": Number(zh_val),							//综合评分 1 ：非常满意，2：满意 3：基本满意 4：不满意,示例值(1) 5:非常不满意
		"qualityEvaluate": Number(zl_val),					//服务质量评分
		"attitudeEvaluate": Number(td_val),					//服务态度评分
		"systemEvaluate": Number(xt_val),					//系统使用评分
		respectAndSecret: Number(zz_val),					//尊重患者评分
		civilizedQuality: Number(wm_val),					//文明礼貌评分
		disciplineIntegrity: Number(zj_val),				//遵纪守法评分
		treatStandardize: Number(yb_val),					//因病施治评分
		"commentDetail": comment_detail,			//评价内容,示例值(非常满意)
		"advice": advice,							//投诉建议
		"doctorId": parseInt(doctor_id),			//医生主键,示例值(60)
		"inquiryPatientId": parseInt(inquirypatientId),			//问诊患者信息主键
		"userType": userJson.type								//问诊人类型 P:个人 S门店
	};
	newAjaxPost("/h5/inquiryLog/comment", paramJson, endInquiryOk);
	return true;
}

function endInquiryOk(jsonInfo) {
	if (jsonInfo.code == 1) {
		msgInfo('结束成功');
		// return
		var isIos = checkWxAndIos();
		if (isIos && getQst("log_type") == '1') {
			//		location.reload() ;
			// setTimeout(function () {
			// window.opener=null;
			// window.open('','_self');

			goPage('inquiry_skip.htm')
			// }, 1000);
		} else {
			goPage('recipe_list.htm')
		}
	}
}

// 输入法遮掩聊天板内容（未完成）/判断是否TV端
function calChatHeight() {
	var winH = $(window).height();
	var chatH;
	if (Number(log_type) == '1') {			//视频
		chatH = winH - 340;
		$('#divCameraMic').show().css('visibility', 'visible');
		// $("#footer").css("position","static");
		// $('#divChatLog').css("margin-top", "167px");
	} else {							//图文
		chatH = winH - 100;
		$('#divCameraMic').hide();
		// $("#footer").css("position","absolute");
		// $('#divChatLog').css("margin-top", "0px");
	}
	//alert(chatH);
	// $('#chat_Log').height(chatH);

	// 判断是否TV端
	var tvflag = getQst("tvflag");
	if (tvflag == 1) {
		$('#videoDiv2').css({ "display": "none" })
		$('#videoDiv1').attr("class", "bvideo");
	} else {
		//什么都不做
	}
}

function nothinglrsj(str) {
	console.log(str);
	if (str) {
		var str_Y = str.substring(0, 4);
		var str_M = str.substring(5, 7);
		var str_D = str.substring(8, 10);
		return str_Y + str_M + str_D;
	}
	else{
		return ""
	}
}

function nothingFun(str, txt) {
	if (isUndefinedAndEmpty(str)) {
		return txt
	} else {
		return str
	}
}

// 根据图片上传状态修改提示语
var uploadingPic = false
//图片
var imgs = new Array();
$(function () {
	var tmpl = '<div style="width:79px;height:79px;margin-top:30px;float: left;margin-right:20px;position: relative;"><div class="picClose" style="position: absolute;width: 20px;top: -10px;right: -10px;"><img width="100%" src="../res/images/close.jpg"></div><li class="weui-uploader__file" style="background-image:url(#url#)"></li></div>',
		$gallery = $("#gallery"), $galleryImg = $("#galleryImg"),
		$galleryImgShow = $("#gallery_img_show"), $galleryShow = $("#gallery_show"),
		$uploaderInput = $("#uploaderInput"), $uploaderFiles = $("#uploaderFiles");
	var $galleryImg = $(".weui-gallery__img"); //相册图片地址
	var $gallery = $(".weui-gallery");
	$uploaderInput.on("change", function (e) {
		var src, url = window.URL || window.webkitURL || window.mozURL, files = e.target.files;
		var file = e.target.value;
		var formData = new FormData();
		//获取当前时间戳加上获取的文件后缀 为文件名
		var filename = new Date().getTime() + getSuffix(file);
		var str = filename.substring(filename.length - 4);
		if (str != '.gif' && str != 'jpeg' && str != '.jpg' && str != '.png') {
			msgInfo('请上传图片格式的文件！')
			return
		}
		$(".weui-uploader__input-box").hide()
		uploadingPic = true
		//注意formData里append添加的键的大小写
		formData.append('key', ossdata.dir + filename); //存储在oss的文件路径
		formData.append('OSSAccessKeyId', ossdata.accessid); //accessKeyId
		formData.append('policy', ossdata.policy); //policy
		formData.append('Signature', ossdata.signature); //签名
		formData.append('callback', ossdata.callback); //签名
		//如果是base64文件，那么直接把base64字符串转成blob对象进行上传就可以了
		formData.append("file", e.target.files[0]);
		formData.append('success_action_status', 200); //成功后返回的操作码
		var fileUrl = ossdata.host + '/' + 'ceshi/' + filename;
		$.ajax({
			type: 'POST',
			data: formData,
			processData: false,//这里默认为true,必须手动改为false
			contentType: false,//这里必须手动改为false,避免出现解析错误
			cache: false,//缓存必须改为false,保证每次都能读取最新数据
			url: ossdata.host,
			success: function (res) {
				if (res.code == 1) {		//上传成功
					msgInfo('图片上传成功', 1200);
					Picdata = res.data
					uploadingPic = false
				}
			},
			error: function (error) {
				console.log(error);//文件上传失败打印错误信息
				$(".weui-uploader__input-box").show()
				uploadingPic = false
			}
		})
		for (var i = 0, len = files.length; i < len; ++i) {
			var file = files[i];
			if (url) {
				src = url.createObjectURL(file);
			} else {
				src = e.target.result;
			}
			$uploaderFiles.html($(tmpl.replace('#url#', src)));
		}
	});

	$uploaderFiles.on("click", "li", function () {
		$galleryImg.attr("style", this.getAttribute("style"));
		$gallery.fadeIn(100);
	});
	$gallery.on("click", function () {
		$gallery.fadeOut(100);
	});
	$uploaderFiles.on("click", ".picClose", function () {
		console.log(1)
		Picdata = ''
		$(".weui-uploader__input-box").show()
		$("#uploaderFiles").html('');
	});
})

function saveImg() {
	if (!Picdata) {
		msgInfo(uploadingPic ? '请等待图片上传完毕' : '请先上传图片', 1000)
		return;
	}
	newUpdateUserHeadImg(Picdata)
}

// 判断是否ios
function checkWxAndIos() {
	var u = navigator.userAgent;
	var ua = navigator.userAgent.toLowerCase();
	var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
	if (isIOS)
		return true;
	else
		return false;
}

function formatDate(date, format) {
	if (format === undefined) {
		format = 'YY-MM-DD hh:mm:ss';
	}

	var year = date.getFullYear(),
		month = date.getMonth() + 1,//月份是从0开始的
		day = date.getDate(),
		hour = date.getHours(),
		min = date.getMinutes(),
		sec = date.getSeconds();
	var preArr = Array.apply(null, Array(10)).map(function (elem, index) {
		return '0' + index;
	});
	var newTime = format.replace(/YY/g, year)
		.replace(/MM/g, preArr[month] || month)
		.replace(/DD/g, preArr[day] || day)
		.replace(/hh/g, preArr[hour] || hour)
		.replace(/mm/g, preArr[min] || min)
		.replace(/ss/g, preArr[sec] || sec);

	return newTime;
}

//获取测量条件
function GetConditionList() {
	var params = ''
	newAjaxPost("/h5/measuringCondition/getMeasuringConditionList", params, GetConditionListOk);
}
function GetConditionListOk(jsonInfo) {
	var data;
	if (jsonInfo.code == 1) {
		data = jsonInfo.data.list
		for (var i = 0; i < data.length; i++) {
			ConditionListName[i] = data[i].conditionName
		}
		$("#text2").picker({
			title: "测量条件",
			toolbarCloseText: '确定',
			cols: [{
				textAlign: 'center',
				values: ConditionListName,
			}],
			onClose: function (result) {
				ConditionName = result.value[0]
			},
		});
	} else {
		msgInfo(jsonInfo.msg);
	}
}
//获取本次问诊的测量数据（查看有没有数据)
function getMeasureData() {
	var params = {
		"current": 1,  //当前页面
		"identityCard": "",	//身份证号码，获取单个患者需要传入
		"logId": log_id,	//获取本次问诊的测量数据需要传入logId
		"size": 10	//每页大小
	}
	newAjaxPost("/h5/inquiryLog/getMeasureDataList", params, getMeasureDataOk);
}
function getMeasureDataOk(jsonInfo) {
	if (jsonInfo.code == 1) {
		data = jsonInfo.data
		if (data.total > 0) {
			//有数据
			isData = 1;
			$("#dataAnimalHeat").val(data.list[0].dataAnimalHeat);
			$("#text2").val(data.list[0].dataCondition);
			$("#dataDbp").val(data.list[0].dataDbp);
			$("#dataGlu").val(data.list[0].dataGlu);
			$("#dataHeartRate").val(data.list[0].dataHeartRate);
			$("#dataRr").val(data.list[0].dataRr);
			$("#dataSbp").val(data.list[0].dataSbp);
		} else {
			//没数据
		}
	} else {
		msgInfo(jsonInfo.msg);
	}
}
//添加与更新测量数据
function addData() {
	var dataAnimalHeat, text2, dataDbp, dataGlu, dataHeartRate, dataRr, dataSbp;
	dataAnimalHeat = $("#dataAnimalHeat").val()
	text2 = $("#text2").val()
	dataDbp = $("#dataDbp").val()
	dataGlu = $("#dataGlu").val()
	dataHeartRate = $("#dataHeartRate").val()
	dataRr = $("#dataRr").val()
	dataSbp = $("#dataSbp").val()
	var params = {
		"dataAnimalHeat": dataAnimalHeat,
		"dataCondition": text2,
		"dataDbp": dataDbp,
		"dataGlu": dataGlu,
		"dataHeartRate": dataHeartRate,
		"dataParameter": "3.61~6.11mmol/L(65~110mg/dl)",
		"dataRr": dataRr,
		"dataSbp": dataSbp,
		"logId": log_id,
		// "remarks": "",
		// "state": 0
	}
	if (isEmpty(dataAnimalHeat) && isEmpty(text2) && isEmpty(dataDbp) && isEmpty(dataGlu) && isEmpty(dataHeartRate) && isEmpty(dataRr) && isEmpty(dataSbp)) {
		msgInfo('至少要输入一项测量内容');
		return;
	} else if (isData == 0) {
		newAjaxPost("/h5/inquiryLog/addMeasureData", params, addDataOk);
	} else {
		newAjaxPost("/h5/inquiryLog/updateMeasureData", params, updateDataOk);
	}
}
function addDataOk(jsonInfo) {
	if (jsonInfo.code == 1) {
		isData = 1;
		msgInfo("添加成功");
		pop = 0;
		$.closePopup(); //关闭
	} else {
		msgInfo(jsonInfo.msg);
	}
}
function updateDataOk(jsonInfo) {
	if (jsonInfo.code == 1) {
		isData = 1
		msgInfo("更新成功");
		pop = 0;
		$.closePopup(); //关闭
	} else {
		msgInfo(jsonInfo.msg);
	}
}
//获取历史数据
function historyData() {
	var params = {
		"current": 1,
		"identityCard": patientIdcard,
		"logId": '',
		"size": 10
	}
	newAjaxPost("/h5/inquiryLog/getMeasureDataList", params, historyDataOk);
}
function historyDataOk(jsonInfo) {
	var historyList = '', i = 0;
	$("#dateHistory").removeClass('weui-popup__container--visible')
	$("#dateHistory").popup(); //打开
	if (jsonInfo.code == 1) {
		data = jsonInfo.data
		if (data.total > 0) {
			//有数据
			for (; i < data.list.length; i++) {
				historyList += '<div class="weui-cell" style="display: block;">'
				//1
				if (data.list[i].createTime == '') {
					historyList += '<div class="line"><div class="weui-cell__hd inline">录入时间：</div><div class="weui-cell__bd inline">--</div></div>'
				} else {
					historyList += '<div class="line"><div class="weui-cell__hd inline">录入时间：</div><div class="weui-cell__bd inline">' + data.list[i].createTime + '</div></div>'
				}
				//2
				if (data.list[i].dataAnimalHeat == '') {
					historyList += '<div class="line"><div class="weui-cell__hd inline">体温(°C)：</div><div class="weui-cell__bd inline">--</div></div>'
				} else {
					historyList += '<div class="line"><div class="weui-cell__hd inline">体温(°C)：</div><div class="weui-cell__bd inline">' + data.list[i].dataAnimalHeat + '</div></div>'
				}
				//3
				if (data.list[i].dataRr == '') {
					historyList += '<div class="line"><div class="weui-cell__hd inline">呼吸频率(次/分钟)：</div><div class="weui-cell__bd inline">--</div></div>'
				} else {
					historyList += '<div class="line"><div class="weui-cell__hd inline">呼吸频率(次/分钟)：</div><div class="weui-cell__bd inline">' + data.list[i].dataRr + '</div></div>'
				}
				//4
				if (data.list[i].dataDbp == '') {
					historyList += '<div class="line"><div class="weui-cell__hd inline">舒张压(mmHg)：</div><div class="weui-cell__bd inline">--</div></div>'
				} else {
					historyList += '<div class="line"><div class="weui-cell__hd inline">舒张压(mmHg)：</div><div class="weui-cell__bd inline">' + data.list[i].dataDbp + '</div></div>'
				}
				//5
				if (data.list[i].dataSbp == '') {
					historyList += '<div class="line"><div class="weui-cell__hd inline">收缩压(mmHg)：</div><div class="weui-cell__bd inline">--</div></div>'
				} else {
					historyList += '<div class="line"><div class="weui-cell__hd inline">收缩压(mmHg)：</div><div class="weui-cell__bd inline">' + data.list[i].dataSbp + '</div></div>'
				}
				//6
				if (data.list[i].dataHeartRate == '') {
					historyList += '<div class="line"><div class="weui-cell__hd inline">心率(次/分钟)：</div><div class="weui-cell__bd inline">--</div></div>'
				} else {
					historyList += '<div class="line"><div class="weui-cell__hd inline">心率(次/分钟)：</div><div class="weui-cell__bd inline">' + data.list[i].dataHeartRate + '</div></div>'
				}
				//7
				if (data.list[i].dataGlu == '') {
					historyList += '<div class="line"><div class="weui-cell__hd inline">血糖(mmol/L)：</div><div class="weui-cell__bd inline">--</div></div>'
				} else {
					historyList += '<div class="line"><div class="weui-cell__hd inline">血糖(mmol/L)：</div><div class="weui-cell__bd inline">' + data.list[i].dataGlu + '</div></div>'
				}
				//8
				if (data.list[i].dataCondition == '') {
					historyList += '<div class="line"><div class="weui-cell__hd inline">测量条件：</div><div class="weui-cell__bd inline">--</div></div>'
				} else {
					historyList += '<div class="line"><div class="weui-cell__hd inline">测量条件：</div><div class="weui-cell__bd inline">' + data.list[i].dataCondition + '</div></div>'
				}
				//9
				if (data.list[i].dataParameter == '') {
					historyList += '<div class="line"><div class="weui-cell__hd inline">测量参考：</div><div class="weui-cell__bd inline">--</div></div>'
				} else {
					historyList += '<div class="line"><div class="weui-cell__hd inline">测量参考：</div><div class="weui-cell__bd inline">' + data.list[i].dataParameter + '</div></div>'
				}
				historyList += '</div>'
			}
			console.log(historyList)
			$(".dataShow").html(historyList)
		} else {
			//没数据
			$(".dataShow").html('<div style="text-align: center;" class="weui-cell">暂无测量数据</div>')
		}
	} else {
		msgInfo(jsonInfo.msg);
	}
}